home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 2 / Apprentice-Release2.iso / Tools / Languages / GCC 1.37.1r14 / usr / lib / stdlib / radixsort.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-03-20  |  9.1 KB  |  297 lines  |  [TEXT/CPED]

  1. /*-
  2.  * Copyright (c) 1990 The Regents of the University of California.
  3.  * All rights reserved.
  4.  *
  5.  * Redistribution and use in source and binary forms, with or without
  6.  * modification, are permitted provided that the following conditions
  7.  * are met:
  8.  * 1. Redistributions of source code must retain the above copyright
  9.  *    notice, this list of conditions and the following disclaimer.
  10.  * 2. Redistributions in binary form must reproduce the above copyright
  11.  *    notice, this list of conditions and the following disclaimer in the
  12.  *    documentation and/or other materials provided with the distribution.
  13.  * 3. All advertising materials mentioning features or use of this software
  14.  *    must display the following acknowledgement:
  15.  *    This product includes software developed by the University of
  16.  *    California, Berkeley and its contributors.
  17.  * 4. Neither the name of the University nor the names of its contributors
  18.  *    may be used to endorse or promote products derived from this software
  19.  *    without specific prior written permission.
  20.  *
  21.  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
  22.  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  23.  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  24.  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
  25.  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  26.  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  27.  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  28.  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  29.  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  30.  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  31.  * SUCH DAMAGE.
  32.  */
  33.  
  34. #if defined(LIBC_SCCS) && !defined(lint)
  35. static char sccsid[] = "@(#)radixsort.c    5.7 (Berkeley) 2/23/91";
  36. #endif /* LIBC_SCCS and not lint */
  37.  
  38. #include <sys/types.h>
  39. #include <limits.h>
  40. #include <stdlib.h>
  41. #include <stddef.h>
  42. #include <string.h>
  43.  
  44. /*
  45.  * __rspartition is the cutoff point for a further partitioning instead
  46.  * of a shellsort.  If it changes check __rsshell_increments.  Both of
  47.  * these are exported, as the best values are data dependent.
  48.  */
  49. #define    NPARTITION    40
  50. int __rspartition = NPARTITION;
  51. int __rsshell_increments[] = { 4, 1, 0, 0, 0, 0, 0, 0 };
  52.  
  53. /*
  54.  * Stackp points to context structures, where each structure schedules a
  55.  * partitioning.  Radixsort exits when the stack is empty.
  56.  *
  57.  * If the buckets are placed on the stack randomly, the worst case is when
  58.  * all the buckets but one contain (npartitions + 1) elements and the bucket
  59.  * pushed on the stack last contains the rest of the elements.  In this case,
  60.  * stack growth is bounded by:
  61.  *
  62.  *    limit = (nelements / (npartitions + 1)) - 1;
  63.  *
  64.  * This is a very large number, 52,377,648 for the maximum 32-bit signed int.
  65.  *
  66.  * By forcing the largest bucket to be pushed on the stack first, the worst
  67.  * case is when all but two buckets each contain (npartitions + 1) elements,
  68.  * with the remaining elements split equally between the first and last
  69.  * buckets pushed on the stack.  In this case, stack growth is bounded when:
  70.  *
  71.  *    for (partition_cnt = 0; nelements > npartitions; ++partition_cnt)
  72.  *        nelements =
  73.  *            (nelements - (npartitions + 1) * (nbuckets - 2)) / 2;
  74.  * The bound is:
  75.  *
  76.  *    limit = partition_cnt * (nbuckets - 1);
  77.  *
  78.  * This is a much smaller number, 4590 for the maximum 32-bit signed int.
  79.  */
  80. #define    NBUCKETS    (UCHAR_MAX + 1)
  81.  
  82. typedef struct _stack {
  83.     const u_char **bot;
  84.     int indx, nmemb;
  85. } CONTEXT;
  86.  
  87. #define    STACKPUSH { \
  88.     stackp->bot = p; \
  89.     stackp->nmemb = nmemb; \
  90.     stackp->indx = indx; \
  91.     ++stackp; \
  92. }
  93. #define    STACKPOP { \
  94.     if (stackp == stack) \
  95.         break; \
  96.     --stackp; \
  97.     bot = stackp->bot; \
  98.     nmemb = stackp->nmemb; \
  99.     indx = stackp->indx; \
  100. }
  101.  
  102. /*
  103.  * A variant of MSD radix sorting; see Knuth Vol. 3, page 177, and 5.2.5,
  104.  * Ex. 10 and 12.  Also, "Three Partition Refinement Algorithms, Paige
  105.  * and Tarjan, SIAM J. Comput. Vol. 16, No. 6, December 1987.
  106.  *
  107.  * This uses a simple sort as soon as a bucket crosses a cutoff point,
  108.  * rather than sorting the entire list after partitioning is finished.
  109.  * This should be an advantage.
  110.  *
  111.  * This is pure MSD instead of LSD of some number of MSD, switching to
  112.  * the simple sort as soon as possible.  Takes linear time relative to
  113.  * the number of bytes in the strings.
  114.  */
  115.  
  116. #if __STDC__
  117. static void shellsort(register const u_char **p, register int indx, register int nmemb, register const u_char *tr);
  118. #else
  119. static void shellsort();
  120. #endif
  121.  
  122. int
  123. #if __STDC__
  124. radixsort(const u_char **l1, int nmemb, const u_char *tab, u_char endbyte)
  125. #else
  126. radixsort(l1, nmemb, tab, endbyte)
  127.     const u_char **l1;
  128.     register int nmemb;
  129.     const u_char *tab;
  130.     u_char endbyte;
  131. #endif
  132. {
  133.     register int i, indx, t1, t2;
  134.     register const u_char **l2;
  135.     register const u_char **p;
  136.     register const u_char **bot;
  137.     register const u_char *tr;
  138.     CONTEXT *stack, *stackp;
  139.     int c[NBUCKETS + 1], max;
  140.     u_char ltab[NBUCKETS];
  141.  
  142.     if (nmemb <= 1)
  143.         return(0);
  144.  
  145.     /*
  146.      * T1 is the constant part of the equation, the number of elements
  147.      * represented on the stack between the top and bottom entries.
  148.      * It doesn't get rounded as the divide by 2 rounds down (correct
  149.      * for a value being subtracted).  T2, the nelem value, has to be
  150.      * rounded up before each divide because we want an upper bound;
  151.      * this could overflow if nmemb is the maximum int.
  152.      */
  153.     t1 = ((__rspartition + 1) * (NBUCKETS - 2)) >> 1;
  154.     for (i = 0, t2 = nmemb; t2 > __rspartition; i += NBUCKETS - 1)
  155.         t2 = ((t2 + 1) >> 1) - t1;
  156.     if (i) {
  157.         if (!(stack = stackp = (CONTEXT *)malloc(i * sizeof(CONTEXT))))
  158.             return(-1);
  159.     } else
  160.         stack = stackp = NULL;
  161.  
  162.     /*
  163.      * There are two arrays, one provided by the user (l1), and the
  164.      * temporary one (l2).  The data is sorted to the temporary stack,
  165.      * and then copied back.  The speedup of using index to determine
  166.      * which stack the data is on and simply swapping stacks back and
  167.      * forth, thus avoiding the copy every iteration, turns out to not
  168.      * be any faster than the current implementation.
  169.      */
  170.     if (!(l2 = (const u_char **)malloc(sizeof(u_char *) * nmemb)))
  171.         return(-1);
  172.  
  173.     /*
  174.      * Tr references a table of sort weights; multiple entries may
  175.      * map to the same weight; EOS char must have the lowest weight.
  176.      */
  177.     if (tab)
  178.         tr = tab;
  179.     else {
  180.         for (t1 = 0, t2 = endbyte; t1 < t2; ++t1)
  181.             ltab[t1] = t1 + 1;
  182.         ltab[t2] = 0;
  183.         for (t1 = endbyte + 1; t1 < NBUCKETS; ++t1)
  184.             ltab[t1] = t1;
  185.         tr = ltab;
  186.     }
  187.  
  188.     /* First sort is entire stack */
  189.     bot = l1;
  190.     indx = 0;
  191.  
  192.     for (;;) {
  193.         /* Clear bucket count array */
  194.         bzero((char *)c, sizeof(c));
  195.  
  196.         /*
  197.          * Compute number of items that sort to the same bucket
  198.          * for this index.
  199.          */
  200.         for (p = bot, i = nmemb; --i >= 0;)
  201.             ++c[tr[(*p++)[indx]]];
  202.  
  203.         /*
  204.          * Sum the number of characters into c, dividing the temp
  205.          * stack into the right number of buckets for this bucket,
  206.          * this index.  C contains the cumulative total of keys
  207.          * before and included in this bucket, and will later be
  208.          * used as an index to the bucket.  c[NBUCKETS] contains
  209.          * the total number of elements, for determining how many
  210.          * elements the last bucket contains.  At the same time
  211.          * find the largest bucket so it gets pushed first.
  212.          */
  213.         for (i = max = t1 = 0, t2 = __rspartition; i <= NBUCKETS; ++i) {
  214.             if (c[i] > t2) {
  215.                 t2 = c[i];
  216.                 max = i;
  217.             }
  218.             t1 = c[i] += t1;
  219.         }
  220.  
  221.         /*
  222.          * Partition the elements into buckets; c decrements through
  223.          * the bucket, and ends up pointing to the first element of
  224.          * the bucket.
  225.          */
  226.         for (i = nmemb; --i >= 0;) {
  227.             --p;
  228.             l2[--c[tr[(*p)[indx]]]] = *p;
  229.         }
  230.  
  231.         /* Copy the partitioned elements back to user stack */
  232.         bcopy(l2, bot, nmemb * sizeof(u_char *));
  233.  
  234.         ++indx;
  235.         /*
  236.          * Sort buckets as necessary; don't sort c[0], it's the
  237.          * EOS character bucket, and nothing can follow EOS.
  238.          */
  239.         for (i = max; i; --i) {
  240.             if ((nmemb = c[i + 1] - (t1 = c[i])) < 2)
  241.                 continue;
  242.             p = bot + t1;
  243.             if (nmemb > __rspartition)
  244.                 STACKPUSH
  245.             else
  246.                 shellsort(p, indx, nmemb, tr);
  247.         }
  248.         for (i = max + 1; i < NBUCKETS; ++i) {
  249.             if ((nmemb = c[i + 1] - (t1 = c[i])) < 2)
  250.                 continue;
  251.             p = bot + t1;
  252.             if (nmemb > __rspartition)
  253.                 STACKPUSH
  254.             else
  255.                 shellsort(p, indx, nmemb, tr);
  256.         }
  257.         /* Break out when stack is empty */
  258.         STACKPOP
  259.     }
  260.  
  261.     free((char *)l2);
  262.     free((char *)stack);
  263.     return(0);
  264. }
  265.  
  266. /*
  267.  * Shellsort (diminishing increment sort) from Data Structures and
  268.  * Algorithms, Aho, Hopcraft and Ullman, 1983 Edition, page 290;
  269.  * see also Knuth Vol. 3, page 84.  The increments are selected from
  270.  * formula (8), page 95.  Roughly O(N^3/2).
  271.  */
  272. static void
  273. shellsort(p, indx, nmemb, tr)
  274.     register const u_char **p, *tr;
  275.     register int indx, nmemb;
  276. {
  277.     register u_char ch;
  278.     register const u_char *s1, *s2;
  279.     register int incr, *incrp, t1, t2;
  280.  
  281.     for (incrp = __rsshell_increments; incr = *incrp++;)
  282.         for (t1 = incr; t1 < nmemb; ++t1)
  283.             for (t2 = t1 - incr; t2 >= 0;) {
  284.                 s1 = p[t2] + indx;
  285.                 s2 = p[t2 + incr] + indx;
  286.                 while ((ch = tr[*s1++]) == tr[*s2] && ch)
  287.                     ++s2;
  288.                 if (ch > tr[*s2]) {
  289.                     s1 = p[t2];
  290.                     p[t2] = p[t2 + incr];
  291.                     p[t2 + incr] = s1;
  292.                     t2 -= incr;
  293.                 } else
  294.                     break;
  295.             }
  296. }
  297.